import { login } from '@/api/user'
import { getToken, setToken, removeToken, getUserInfo, setUserInfo } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: getUserInfo(),
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
}

const actions = {
  login({ commit, state }, userInfo) {
    console.log('userInfo',userInfo)
    const { username, password} = userInfo
    return new Promise((resolve, reject) => {
      console.log('login', username, password)
      commit('SET_TOKEN', 'data.token')
      setToken('data.token')
      setUserInfo({
        username,
        password
      })
      commit('SET_USERINFO', {
        username,
        password
      })
      resolve()
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

